<template>
    <div class="add-invoice-management">
      <!-- 页面标题 -->
      <div class="page-header">
        <h2>{{ isViewMode ? '查看发票' : '编辑发票' }}</h2>
        <div class="header-actions">
          <button @click="handleCancel" class="btn btn-secondary">
            <i class="icon-back"></i>
            返回
          </button>
        </div>
      </div>
      
      <!-- 表单区域 -->
      <div class="form-section">
        <form @submit.prevent="handleSubmit" class="invoice-form">
          <!-- 开票单位 -->
          <div class="form-item">
            <label class="form-label required">开票单位</label>
            <input 
              v-model="formData.distributorName" 
              type="text" 
              class="form-input"
              placeholder="请输入开票单位"
              :readonly="isViewMode"
              required
            />
          </div>
  
     
  
          <!-- 发票类型 -->
          <div class="form-item">
            <label class="form-label required">发票类型</label>
            <div class="radio-group">
              <label class="radio-item">
                <input 
                  type="radio" 
                  v-model="formData.invoiceType" 
                  :value="false"
                  class="radio-input"
                />
                <span class="radio-label">普通发票</span>
              </label>
              <label class="radio-item">
                <input 
                  type="radio" 
                  v-model="formData.invoiceType" 
                  :value="true"
                  class="radio-input"
                />
                <span class="radio-label">增值税发票</span>
              </label>
            </div>
          </div>
  
          <!-- 发票金额 -->
          <div class="form-item">
            <label class="form-label required">发票金额</label>
              <input 
                v-model="formData.invoiceAmount" 
                type="number" 
                step="0.01"
                class="form-input"
                placeholder="请输入发票金额"
                @input="calculateTaxAmount"
                :readonly="isViewMode"
                required
              />
          </div>
  
          <!-- 税率 -->
          <div class="form-item">
            <label class="form-label required">税率</label>
            <input 
              v-model="taxRateInput" 
              type="number" 
              step="0.1"
              class="form-input"
              placeholder="请输入梯度"
              @input="updateTaxRate"
              :readonly="isViewMode"
              required
            />
          </div>
  
          <!-- 税额 -->
          <div class="form-item">
            <label class="form-label">税额</label>
            <input 
              v-model="formData.taxAmount" 
              type="number" 
              step="0.01"
              class="form-input readonly"
              placeholder="自动计算"
              readonly
            />
          </div>
  
          <!-- 开票日期 -->
          <div class="form-item">
            <label class="form-label required">开票日期</label>
            <div class="date-input-wrapper">
              <input 
                v-model="formData.invoiceDate" 
                type="date" 
                class="form-input date-input"
                placeholder="请选择开票日期"
                :readonly="isViewMode"
                required
              />
              <span class="calendar-icon">📅</span>
            </div>
          </div>
  
          <!-- 备注 -->
          <div class="form-item">
            <label class="form-label">备注</label>
            <textarea 
              v-model="formData.notes" 
              class="form-textarea"
              placeholder="请输入备注信息"
              :readonly="isViewMode"
              rows="3"
            ></textarea>
          </div>
  
    
  
          <!-- 操作按钮 -->
          <div class="form-actions">
            <button v-if="!isViewMode" type="submit" class="btn btn-primary" :disabled="loading">
              <span v-if="loading">保存中...</span>
              <span v-else>更新</span>
            </button>
            <button type="button" @click="handleCancel" class="btn btn-cancel">
              {{ isViewMode ? '关闭' : '取消' }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </template>
  
<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { setApi } from '@/api'

// 路由实例
const router = useRouter()
const route = useRoute()

// 获取发票ID和模式
const invoiceId = route.params.id as string
const isViewMode = computed(() => route.query.mode === 'view')
  
  // 表单数据
  const formData = reactive({
    distributorName: '',
    invoiceNo: '',
    invoiceType: false, // 布尔值：false=普通发票，true=增值税发票
    invoiceAmount: 0,
    taxRate: 0,
    taxAmount: 0,
    invoiceDate: '',
    notes: '',
    preparer: '',
    createdTime: '',
    createdBy: '',
    lastModifiedBy: '',
    purchaseSalesInvoices: false
  })
  
  // 税率输入（百分比形式）
  const taxRateInput = ref('')
  
// 加载状态
const loading = ref(false)

// 获取发票详情
const fetchInvoiceDetails = async () => {
  try {
    loading.value = true
    const response = await setApi.getInvoiceDetails(parseInt(invoiceId))
    
    if (response.code === 200) {
      const data = response.data
      
      // 填充表单数据
      formData.distributorName = data.distributorName || ''
      formData.invoiceNo = data.invoiceNo || ''
      formData.invoiceType = data.invoiceType === 'True' || data.purchaseSalesInvoices === true
      formData.invoiceAmount = data.invoiceAmount || 0
      formData.taxRate = (data.taxRate || 0) * 100 // 转换为百分比
      formData.taxAmount = data.taxAmount || 0
      formData.invoiceDate = data.invoiceDate ? data.invoiceDate.split('T')[0] : ''
      formData.notes = data.notes || ''
      formData.preparer = data.preparer || ''
      formData.createdTime = data.createdTime || ''
      formData.createdBy = data.createdBy || ''
      formData.lastModifiedBy = data.lastModifiedBy || ''
      formData.purchaseSalesInvoices = data.purchaseSalesInvoices || false
      
      // 设置税率输入框
      taxRateInput.value = formData.taxRate.toString()
    } else {
      alert('获取发票详情失败: ' + response.message)
    }
  } catch (error) {
    alert('获取发票详情出错，请重试')
  } finally {
    loading.value = false
  }
}
  
  // 更新税率
  const updateTaxRate = () => {
    formData.taxRate = parseFloat(taxRateInput.value) || 0
    calculateTaxAmount()
  }
  
  // 计算税额
  const calculateTaxAmount = () => {
    if (formData.invoiceAmount && formData.taxRate) {
      formData.taxAmount = parseFloat((formData.invoiceAmount * formData.taxRate / 100).toFixed(2))
    } else {
      formData.taxAmount = 0
    }
  }
  
  // 方法
  const handleCancel = () => {
    router.back()
  }
  
  const handleSubmit = async () => {
    try {
      loading.value = true
      
      // 验证必填字段
      if (!formData.distributorName.trim()) {
        alert('请输入经销商名称')
        return
      }
     
      if (!formData.invoiceAmount || formData.invoiceAmount <= 0) {
        alert('请输入有效的发票金额')
        return
      }
      if (!taxRateInput.value) {
        alert('请输入税率')
        return
      }
      if (!formData.invoiceDate) {
        alert('请选择开票日期')
        return
      }
      
  
      // 准备提交数据
      const submitData = {
        id: parseInt(invoiceId),
        distributorName: formData.distributorName,
        invoiceNo: formData.invoiceNo,
        invoiceType: formData.invoiceType,
        invoiceAmount: parseFloat(formData.invoiceAmount.toString()),
        taxRate: formData.taxRate / 100,
        taxAmount: parseFloat(formData.taxAmount.toString()),
        invoiceDate: new Date(formData.invoiceDate).toISOString(),
        notes: formData.notes,
        preparer: formData.preparer,
        createdTime: formData.createdTime || new Date().toISOString(),
        purchaseSalesInvoices: formData.invoiceType,
        createdBy: formData.createdBy || formData.preparer,
        lastModifiedBy: formData.preparer
      }

      const response = await setApi.updateInboundOutboundInvoice(submitData)

      if (response.code === 200) {
        alert('发票更新成功！')
        handleCancel()
      } else {
        alert('更新失败: ' + response.message)
      }
    } catch (error) {
      alert('更新出错，请重试')
    } finally {
      loading.value = false
    }
  }
  
// 组件挂载时获取发票详情
onMounted(() => {
  if (invoiceId) {
    fetchInvoiceDetails()
  } else {
    // 如果没有ID，设置默认日期（新增模式）
    const today = new Date().toISOString().split('T')[0]
    formData.invoiceDate = today
  }
})
  </script>
  
  <style scoped>
  .add-invoice-management {
    padding: 20px;
    background-color: #f5f5f5;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  /* 页面标题样式 */
  .page-header {
    background: white;
    padding: 20px;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    width: 100%;
    max-width: 600px;
  }

  .page-header h2 {
    margin: 0;
    color: #333;
    font-size: 24px;
  }

  .header-actions {
    display: flex;
    gap: 10px;
  }
  
  /* 表单区域样式 */
  .form-section {
    background: white;
    padding: 40px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    width: 100%;
    max-width: 600px;
  }
  
  .invoice-form {
    display: flex;
    flex-direction: column;
    gap: 20px;
  }
  
  .form-item {
    display: flex;
    align-items: center;
    gap: 20px;
  }
  
  .form-label {
    font-weight: bold;
    color: #333;
    font-size: 14px;
    min-width: 80px;
    text-align: right;
  }
  
  .form-label.required::after {
    content: ' *';
    color: #dc3545;
  }
  
  .form-input, .form-textarea {
    flex: 1;
    padding: 12px 16px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 14px;
    transition: border-color 0.3s;
    background: white;
  }
  
  .form-input:focus, .form-textarea:focus {
    outline: none;
    border-color: #007bff;
  }
  
  .form-input.readonly {
    background-color: #f8f9fa;
    color: #6c757d;
  }
  
  .form-textarea {
    resize: vertical;
    min-height: 80px;
  }
  
  /* 单选框样式 */
  .radio-group {
    display: flex;
    gap: 20px;
    flex: 1;
  }
  
  .radio-item {
    display: flex;
    align-items: center;
    gap: 8px;
    cursor: pointer;
  }
  
  .radio-input {
    width: 16px;
    height: 16px;
    cursor: pointer;
  }
  
  .radio-label {
    font-size: 14px;
    color: #333;
    cursor: pointer;
  }
  
  /* 日期输入样式 */
  .date-input-wrapper {
    position: relative;
    flex: 1;
  }
  
  .date-input {
    padding-right: 40px;
  }
  
  .calendar-icon {
    position: absolute;
    right: 12px;
    top: 50%;
    transform: translateY(-50%);
    font-size: 16px;
    pointer-events: none;
  }
  
  /* 按钮样式 */
  .form-actions {
    display: flex;
    gap: 15px;
    justify-content: center;
    margin-top: 30px;
    padding-top: 20px;
    border-top: 1px solid #eee;
  }
  
  .btn {
    padding: 12px 24px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    font-weight: 500;
    transition: all 0.3s;
    min-width: 100px;
  }
  
  .btn-primary {
    background: #007bff;
    color: white;
  }
  
  .btn-primary:hover:not(:disabled) {
    background: #0056b3;
  }
  
  .btn-primary:disabled {
    background: #6c757d;
    cursor: not-allowed;
  }
  
  .btn-cancel {
    background: white;
    color: #007bff;
    border: 1px solid #007bff;
  }
  
  .btn-cancel:hover {
    background: #f8f9fa;
  }

  /* 图标样式 */
  .icon-back::before {
    content: "←";
  }
  
  /* 响应式设计 */
  @media (max-width: 768px) {
    .add-invoice-management {
      padding: 10px;
    }
    
    .form-section {
      padding: 20px;
    }
    
    .form-item {
      flex-direction: column;
      align-items: flex-start;
      gap: 8px;
    }
    
    .form-label {
      min-width: auto;
      text-align: left;
    }
    
    .form-input, .form-textarea {
      width: 100%;
    }
    
    .radio-group {
      width: 100%;
      justify-content: flex-start;
    }
    
    .form-actions {
      flex-direction: column;
    }
    
    .btn {
      width: 100%;
    }
  }
  </style>